package com.esiran.payadmin.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

public class JWTUtil {
    private static final String SECRET = "cn.s7buy.app";
    private static final String ISSUER_ACCESS_TOKEN = "com.esiran.accessToken";
    private static final String ISSUER_REFRESH_TOKEN = "s7buy.cn.refreshToken";
    public static JWTCreator.Builder createAccessToken(){
        return JWT.create()
                .withIssuer(ISSUER_ACCESS_TOKEN);
    }
    public static JWTCreator.Builder createRefreshToken(){
        return JWT.create()
                .withIssuer(ISSUER_REFRESH_TOKEN);
    }
    public static Algorithm getAlgorithm(){
        return Algorithm.HMAC256(SECRET);
    }
    public static String checkHttpAuthToken(String auth){
        if (auth == null){
            return null;
        }
        return auth.replaceAll("Bearer ","");
    }
    public static String checkAccessToken(String token){
        if (token == null){
            return null;
        }
        DecodedJWT decodedJWT = JWT.require(getAlgorithm()).withIssuer(ISSUER_ACCESS_TOKEN).build().verify(token);
        return decodedJWT.getSubject();
    }
    public static String checkRefreshToken(String token){
        DecodedJWT decodedJWT = JWT.require(getAlgorithm()).withIssuer(ISSUER_REFRESH_TOKEN).build().verify(token);
        return decodedJWT.getSubject();
    }
    public static String getTokenClaim(String token,String key){
        DecodedJWT decodedJWT = JWT.decode(token);
        return decodedJWT.getClaim(key).asString();
    }
}
